package mq_nsq

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/tx7do/kratos-transport/broker"
)

// handler
func BookDataCreator() broker.Any { return &BookData{} }

type BookDataHandler func(_ context.Context, event broker.Event, topic string, headers broker.Headers, msg *BookData) error

func RegisterBookDataHandler(fnc BookDataHandler) broker.Handler {
	return func(ctx context.Context, event broker.Event) error {
		var msg *BookData = nil

		switch t := event.Message().Body.(type) {
		case []byte:
			msg = &BookData{}
			if err := json.Unmarshal(t, msg); err != nil {
				return err
			}
		case string:
			msg = &BookData{}
			if err := json.Unmarshal([]byte(t), msg); err != nil {
				return err
			}
		case *BookData:
			msg = t
		default:
			return fmt.Errorf("unsupported type: %T", t)
		}

		if err := fnc(ctx, event, event.Topic(), event.Message().Headers, msg); err != nil {
			return err
		}

		return nil
	}
}
